<?php

namespace Database\Seeders;

use Illuminate\Database\Seeder;
use Illuminate\Support\Facades\DB;

class RemoveErrorLogMenuSeeder extends Seeder
{
    /**
     * 删除错误日志菜单和权限
     *
     * @return void
     */
    public function run()
    {
        DB::transaction(function () {
            // 1. 删除角色菜单关联（错误日志菜单）
            $menuIds = DB::table('menus')
                ->where('path', '/monitor/error-log')
                ->pluck('id')
                ->toArray();
            
            if (!empty($menuIds)) {
                DB::table('role_menus')
                    ->whereIn('menu_id', $menuIds)
                    ->delete();
                
                echo "已删除 " . count($menuIds) . " 个错误日志菜单的角色关联\n";
            }
            
            // 2. 删除错误日志菜单
            $deletedMenus = DB::table('menus')
                ->where('path', '/monitor/error-log')
                ->delete();
            
            if ($deletedMenus > 0) {
                echo "已删除 {$deletedMenus} 个错误日志菜单\n";
            }
            
            // 3. 删除角色权限关联（错误日志权限）
            $permissionIds = DB::table('permissions')
                ->where('code', 'like', 'error_logs.%')
                ->pluck('id')
                ->toArray();
            
            if (!empty($permissionIds)) {
                DB::table('role_permissions')
                    ->whereIn('permission_id', $permissionIds)
                    ->delete();
                
                echo "已删除 " . count($permissionIds) . " 个错误日志权限的角色关联\n";
            }
            
            // 4. 删除错误日志权限
            $deletedPermissions = DB::table('permissions')
                ->where('code', 'like', 'error_logs.%')
                ->delete();
            
            if ($deletedPermissions > 0) {
                echo "已删除 {$deletedPermissions} 个错误日志权限\n";
            }
            
            // 5. 删除错误日志表（如果存在）
            if (DB::getSchemaBuilder()->hasTable('error_logs')) {
                DB::statement('DROP TABLE IF EXISTS error_logs');
                echo "已删除错误日志表\n";
            }
        });
        
        echo "错误日志菜单和权限清理完成！\n";
    }
}

